import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:keyboard_actions/keyboard_actions.dart';

/// Created by XieXin on 2020/3/26.
/// 适配ScrollView
class XScrollView extends StatelessWidget {
  final List<Widget>? children;
  final EdgeInsetsGeometry? padding;
  final ScrollPhysics? physics;
  final bool shrinkWrap;
  final CrossAxisAlignment crossAxisAlignment;
  final Widget? header;
  final Widget? footer;
  final Widget? emptyWidget;
  final KeyboardActionsConfig? keyboardConfig; //使用EasyRefresh需要禁用这个，跟他冲突了

  /// 键盘外部按下将其关闭
  final TapOutsideBehavior tapOutsideBehavior;
  final bool disableScroll; //ios起作用，禁用滚动

  const XScrollView({
    Key? key,
    this.children,
    this.padding,
    this.physics = const BouncingScrollPhysics(),
    this.shrinkWrap = false,
    this.crossAxisAlignment = CrossAxisAlignment.start,
    this.header,
    this.footer,
    this.emptyWidget,
    this.keyboardConfig,
    this.tapOutsideBehavior = TapOutsideBehavior.translucentDismiss,
    this.disableScroll = false,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Widget contents = Column(
      crossAxisAlignment: crossAxisAlignment,
      children: children ?? [],
    );
    if (emptyWidget == null) {
      ///iOS键盘处理
      if (defaultTargetPlatform == TargetPlatform.iOS &&
          keyboardConfig != null) {
        contents = Padding(
          padding: padding ?? EdgeInsets.zero,
          child: KeyboardActions(
            config: keyboardConfig!,
            tapOutsideBehavior: tapOutsideBehavior,
            disableScroll: disableScroll,
            bottomAvoiderScrollPhysics: physics,
            child: contents,
          ),
        );
      } else {
        contents = CustomScrollView(
          shrinkWrap: shrinkWrap,
          physics: physics,
          slivers: [
            SliverList(
              delegate: SliverChildListDelegate([
                Padding(
                  padding: padding ?? EdgeInsets.zero,
                  child: contents,
                )
              ]),
            ),
          ],
        );
      }
    } else {
      contents = emptyWidget!;
    }

    if (header != null || footer != null) {
      contents = Column(
        children: <Widget>[
          header == null ? const SizedBox.shrink() : SafeArea(child: header!),
          Expanded(child: contents),
          footer == null ? const SizedBox.shrink() : SafeArea(child: footer!),
        ],
      );
    }

    return contents;
  }
}
